// pages/check/index.js
var $ = require('../../utils/ajax.js');
const util = require('../../utils/util.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   * 
   */
  data: {
    list: [],
    inputShowed: false,
    inputVal: "",
    type:1,
    tabs: ["待巡检", "已巡检"],
    sliderOffset: 37,
    sliderLeft: 0,
    checkActiveIndex:0,//0:待处理  1：已处理
    positionArray:[{"id":'',"name":'所有'}],
    positionSelIndex:0,//已选巡检位置

    params: {
      //token: that.data.token,
      "startDate": null,
      "endDate": null,//util.formatTime(new Date()),
      "isExecute": 0,//isExecute=1 已巡检,0未巡检
      "computerRoom":null,//巡检机房
      "limit": getApp().data.limit,
      "page": 1
    },
    pageTotal: 0,
    loadData: { "loadMoreHidden": true, "loadingHidden": true, 'loadMoreText': '暂无数据'},
    scroll: { "scrollTop": 0,"scrollHeight":0},
    undoCheckCount:0,
    userId : app.data.userId,
    debounce: null
  },
  //tab点击事件//待处理/已处理列表 startDate endDate:巡检时间段  包括端点  computerRoom 巡检机房 isExecute: 1 以巡检
  tabClick: function (e) {
    var _this = this;
    let id = e.currentTarget.id;
    _this.setData({
      list:[],
      ['params.isExecute']: id,
      ['params.page']: 1,
      sliderOffset: e.currentTarget.offsetLeft + 40,
      checkActiveIndex: id
    })
    
    _this.doPostDataList(_this, _this.data.params);
  },

  bindStrDateChange: function (e) {
    var strDate = e.detail.value + ' 00:00';
    this.setData({
      list: [],
      ['params.startDate']: strDate,
      ['params.page']: 1
    })
    this.doPostDataList(this, this.data.params);
  },
  bindEndDateChange: function (e) {
    var endDate = e.detail.value + ' 23:59';
    this.setData({
      list: [],
      ['params.endDate']: endDate,
      ['params.page']:1
    })
    this.doPostDataList(this, this.data.params);
  },
  /*位置下拉框选择 */
  bindPositionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let index = e.detail.value;
    var currentId = this.data.positionArray[index].id; // 这个id就是选中项的id
    var params = this.data.params;
    if (currentId != ""){
      params.computerRoom = currentId;
    }
    this.setData({
      list: [],
      params: params,
      positionSelIndex: index,
      ['params.page']:1
    })
    this.doPostDataList(this, this.data.params);
  },
  
  //查询列表信息
  doPostDataList(_this, params){
    _this.setData({
      ['loadData.loadingHidden']: true
    })
    $.post({
      url: getApp().data.app_server + '/weixin/polling/get-polling-record-list',
      data: params,
      header: {'content-type': 'application/json; charset=UTF-8'},
    }).then((res) => {
      console.log(res)
      _this.setData({
        ['loadData.loadingHidden']: false
      })
      let data = res.data.data;
      if (res.data.count > 0) {
        for (var i = 0; i < data.length; i++) {
          data[i].inspectionPlanEntity.inspectionStartDate = util.formatTimeStamp(data[i].inspectionPlanEntity.inspectionStartDate, 'Y-M-D h:m');
          let time = data[i].inspectionCycle -100;
          let flag = 2;//0超时巡检，1已逾期，2正常巡检
          let flagInspection = 1;//0 待巡检，1已巡检
          if (time < new Date().getTime()){
            if (data[i].inspectionExecute){
              flag = 0;
            }else{
              flag = 1;
            }
          }
          if (!data[i].inspectionExecute){
            flagInspection = 0;
          }
          data[i].flagInspection = flagInspection;
          data[i].flag = flag;
          //待巡检人
          var name = '未关联';
          var userIds = '';
          if (data[i].inspectionImplementUsers != null){
            name = '';
            for (var j = 0; j < data[i].inspectionImplementUsers.length; j++) {
              name = data[i].inspectionImplementUsers[j].userName + ',' + name;
              userIds = data[i].inspectionImplementUsers[j].userId + ',' + userIds;
            }
            name = name.substr(0,name.length-1);
            data[i].inspectionImplementUsers = name;
          }
          //是否有执行按钮权限
          var val = app.data.permissions.indexOf('polling:record:exec');
          if ((val > -1 || userIds.indexOf(_this.data.userId) > -1) && !data[i].inspectionExecute ){
            data[i].showExecuteBtn = true;
          }
        }
        var params = _this.data.params;
        var pageTotal = Math.ceil(res.data.count / _this.data.params.limit);
        var undoCheckCount = params.isExecute == 0 ? res.data.count : _this.data.undoCheckCount;
        _this.setData({
          list: _this.data.list.concat(data),//列表拼接
          ['loadData.loadingHidden']: false,
          params: params,
          pageTotal: pageTotal,
          undoCheckCount: undoCheckCount
        })
        if (pageTotal == 1) {
          _this.setData({
            ['loadData.loadMoreText']: '已经到底部了',
            ['loadData.loadMoreHidden']: true
          })
        }
      }else{
        _this.setData({
          list: _this.data.list.concat(data),//列表拼接
          ['loadData.loadMoreText']: '暂无数据'
        })
      }

    }).catch((err) => {
      console.log(err);
    });
  },
  //获取位置下拉框数据
  doGetPositionList(){
    var _this = this;
    $.get({
      url: getApp().data.app_server + '/weixin/computer-room/get-list-all'
    }).then((res) => {
      _this.setData({
        positionArray: _this.data.positionArray.concat(res.data.msg)
      });
    }).catch((err) => {
      console.log(err);
    });
  },

  bindDownLoad: function () {
    var _this = this;
    let debounce = this.data.timeout;
    if (debounce) clearTimeout(debounce);
    let curPage = _this.data.curPage + 1;
    // 防抖函数
    debounce = setTimeout(function () {
      //判断是否是最后一页，最后一页不加载数据了
      console.log('curPage:' + curPage + ',pageTotal:' + _this.data.pageTotal);
      if (_this.data.pageTotal < curPage) {
        _this.setData({
          ['loadData.loadMoreText']: '已经到底部了',
          ['loadData.loadMoreHidden']: true
        })
      }else{
        _this.setData({
          ['params.page']: curPage,
          ['loadData.loadMoreHidden']: false
        })
        _this.doPostDataList(_this, _this.data.params);
      }
    }, 500);
    _this.setData({
      debounce: debounce
    })
  },
  scroll: function (event) {
    //该方法绑定了页面滚动时的事件，我这里记录了当前的position.y的值,为了请求数据之后把页面定位到这里来。
    this.setData({
      ['scroll.scrollTop']: event.detail.scrollTop 
    });
  },
  /*refresh: function (event) {
    //该方法绑定了页面滑动到顶部的事件，然后做上拉刷新
    var _this = this;
    _this.setData({
      list: [],
      scrollTop: 0,
      ['params.page']: 1
    });
    _this.doPostDataList(_this, _this.data.params);
  },*/

  //查看详情
  details(e) {
    var id = e.currentTarget.id;
    var url = 'detail/doneDetail?id=' + id
    console.log(this.data.checkActiveIndex);
    if (this.data.checkActiveIndex == 0 ){
      url = 'detail/todoDetail?id=' + id
    }
    wx.navigateTo({
      url: url
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var strDateTime = util.formatTimeStamp(new Date().getTime(), 'Y-M-D') + ' 00:00'
    var endDateTime = util.formatTimeStamp(new Date().getTime(), 'Y-M-D') + ' 23:59'
    this.setData({
      ['params.startDate']: strDateTime,
      ['params.endDate']: endDateTime
    })
    this.doGetPositionList();//获取所有位置
    this.doPostDataList(this,this.data.params);
    //这里要非常注意，微信的scroll-view必须要设置高度才能监听滚动事件，所以，需要在页面的onLoad事件中给scroll-view的高度赋值
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          ['scroll.scrollHeight']: res.windowHeight - 80,
          undoCheckCount:app.data.undoCheckCount
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})